package com.gr.staffpm.charts;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.wicket.util.io.ByteArrayOutputStream;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.imagemap.ImageMapUtilities;

/**
 * Nice utility to manage the generation of charts.
 * @author Graham Rhodes
 * @date   23 Nov 2010
 */
public class ChartHelper {

    private final JFreeChart chart;
    private final Logger log = Logger.getLogger(ChartHelper.class);
    private final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
    private String imageMapName = "";
    private int width = 520;
    private int height = 400;

    public ChartHelper(JFreeChart chart) {
        this.chart = chart;
    }

    public JFreeChart getChart() {
        return chart;
    }

    public void generate(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public ChartRenderingInfo getRenderingInfo() {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ChartUtilities.writeChartAsPNG(out, chart, width, height, info);
            out.close();
        } catch (IOException e) {
            log.error("Failed writing chart as png. Error was " + e);
        }
        return info;
    }

    public String getImageMap(String name) {
        this.imageMapName = name;
        return ImageMapUtilities.getImageMap(name, getRenderingInfo());
    }

    public String getImageMapName() {
        return imageMapName;
    }
}
